package com.ml4ai.backend.security;

import com.ml4ai.backend.utils.JSONUtil;
import com.ml4ai.backend.utils.RestUtil;
import lombok.Cleanup;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Service;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

/**
 * Created by leecheng on 2017/10/17.
 */
@Service
@Transactional
public class SecurityLoginSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        httpServletRequest.setCharacterEncoding("UTF-8");
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setHeader("Content-Type", "application/json;charset=utf-8");
        httpServletResponse.addHeader("Access-Control-Allow-Origin", "*");
        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        @Cleanup PrintWriter printWriter = new PrintWriter(httpServletResponse.getOutputStream());
        printWriter.print(JSONUtil.toJson(RestUtil.success(httpServletRequest.getSession().getId())));
    }
}
